
package com.bear.cmcc.NetTestHTTP.service;

import com.bear.cmcc.NetTestHTTP.NetworkTestApp;
import com.bear.cmcc.NetTestHTTP.R;
import com.bear.cmcc.NetTestHTTP.component.NetTestConnecInfoBean;
import com.bear.cmcc.NetTestHTTP.component.NetTestLogBean;
import com.bear.cmcc.NetTestHTTP.component.NetTestRoundInfoBean;
import com.bear.cmcc.NetTestHTTP.component.NetTestTimesInfoBean;
import com.bear.cmcc.NetTestHTTP.component.PowerLock;
import com.bear.cmcc.NetTestHTTP.component.ServersConfigBean;
import com.bear.cmcc.NetTestHTTP.constant.FtpConstant;
import com.bear.cmcc.NetTestHTTP.constant.MyCommonConstant;
import com.bear.cmcc.NetTestHTTP.constant.NetTestDBConstant;
import com.bear.cmcc.NetTestHTTP.constant.MyCommonConstant.PrivateActionName;
import com.bear.cmcc.NetTestHTTP.db.NetTestDBControl;
import com.bear.cmcc.NetTestHTTP.util.FtpUtil;
import com.bear.cmcc.NetTestHTTP.util.LocationUtil;
import com.bear.cmcc.NetTestHTTP.util.MyCommonUtil;
import com.bear.cmcc.NetTestHTTP.util.NetTestUtil;
import com.bear.cmcc.NetTestHTTP.util.TimeUtil;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ServiceInfo;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.telephony.CellLocation;
import android.telephony.PhoneStateListener;
import android.telephony.SignalStrength;
import android.telephony.TelephonyManager;
import android.util.Log;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.SocketException;
import java.util.ArrayList;

/**
 * 测试服务
 * 
 * @author suchangjun
 * @add guanyh2013-2-27增加开启服务时停止其他服务，结束后重新开启之前结束的服务
 * @add guanyh2013-2-28增加下载方法，使用log对象和测试单次对象保存过程数据，log测试可正常保存
 * @add guanyh2013-3-1增加手机状态监听，每轮测试结果保存到数据库，每次测试结果保存到数据库，每次小区切换时结果保存到数据库
 * @add guanyh2013-3-2增加connect表的保存，一轮最大速度和最小速度，增加测试过程实时广播
 */
public class NetTestService extends Service {
    static String TAG = "NETTESTSERVICE";

    static String GYH = "GYH";

    ServiceInfo[] ourServices;// 其他service的集合

    ArrayList<String> stopedServicesName;// 暂停掉的其他service的名称集合

    private Thread threadTest;// 测试线程

    private PowerLock powerLock;

    // boolean isContinueTest;// 是否循环测试

    int countTestNum;// 测试次数

    // int countUpTestNum;// 上行测试次数

    int netStrong, maxNetStrong, minNetStrong;

    double oneTimesAverageSpeed, oneTempSpeed, roundMaxSpeed, roundMinSpeed, maxSpeed, minSpeed,
            oneLogAveragespeed, roundAverageSpeed, roundFileSize;// 一次测试的平均速度、临时速度变量、最大速度、最小速度,保存一次log的平均速度

    long roundTimes = 0;

    int fileFQsize = MyCommonConstant.FQSIZE.SIZE_TD;// 下载时缓存分区大小

    String testDownFileName;// 下载文件的文件名

    NetTestLogBean netLogBean;

    NetTestTimesInfoBean netTestTimesInfoBean;

    NetTestRoundInfoBean netTestRoundInfoBean;

    NetTestConnecInfoBean netTestConnectInfoBean;

    MyPhoneStateListener MyListener;

    TelephonyManager telManager;

    int nextTimesID;// round表最后一个pid+1（关联times表的roundID），times表的最后一个pid+1（关联cell表的timesID）

    NetTestDBControl dbControl;

    int actualTestTimes, allTestTimes;// 实际测试的次数，当前是这一轮的第几次测试

    int connectPercent = 1, dropPercent = 1;// 接通率（0表示成功，1表示失败）、掉线率（0表示掉线，1表示没掉线）

    ServersConfigBean serverConfigBean;

    boolean timesFirstContrastSpeed;// 表示每次测试时是否是第一次对比速度，用来过滤掉第一次不保存maxspeed、minspeed

    private ArrayList<Double> fancai = null;// 方差计算需要

    /**
     * 手机状态监听
     * 
     * @author guanyouhui
     */
    private class MyPhoneStateListener extends PhoneStateListener {
        @Override
        public void onSignalStrengthsChanged(SignalStrength signalStrength) {
            super.onSignalStrengthsChanged(signalStrength);
            int asu = signalStrength.getGsmSignalStrength();
            netStrong = -113 + 2 * asu;
            if (netLogBean != null) {
                netLogBean.setNetStrong(netStrong);
            }
            if (maxNetStrong == 0)
                maxNetStrong = netStrong;
            if (minNetStrong == 0)
                minNetStrong = netStrong;

            if (countTestNum > 0) {// 只在测试过程中对比型号强度
                maxNetStrong = (maxNetStrong < netStrong) ? netStrong : maxNetStrong;
                minNetStrong = (minNetStrong > netStrong) ? netStrong : minNetStrong;
            }
        }

        @Override
        public void onCellLocationChanged(CellLocation location) {
            super.onCellLocationChanged(location);
            if (netLogBean != null) {
                NetTestUtil.getNetworkInfo(getBaseContext(), netLogBean);
                NetTestUtil.getLACCI(getBaseContext(), netLogBean);
                if (countTestNum > 0)// 只在测试过程插入数据
                {
                    if (NetTestUtil.isCellChange(location, netLogBean.getLac(), netLogBean.getCi())) {
                        // 小区位置改变时插入数据库小区信息
                        if (!NetTestUtil.hasNetTestCellInfosByTimes(getBaseContext(), nextTimesID,
                                netLogBean.getLac(), netLogBean.getCi())) {
                            if (oneTimesAverageSpeed > 0 || maxSpeed > 0 || minSpeed > 0)// 至少要有一个速度大于0，避免一开始测试发生小区变化就插入，信息不准
                            {
                                NetTestUtil.insertCellInfo(oneTimesAverageSpeed, maxSpeed,
                                        minSpeed, maxNetStrong, minNetStrong, nextTimesID,
                                        getBaseContext(), netLogBean);
                            }
                        }
                    }
                }
            }
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i(TAG, TAG + " onCreate.");
        try {
            if (powerLock == null)
                powerLock = new PowerLock(this, "NetTestService");
            powerLock.acquireWakeLock();
            MyListener = new MyPhoneStateListener();
            telManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
            telManager.listen(MyListener, PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
            telManager.listen(MyListener, PhoneStateListener.LISTEN_CELL_LOCATION);
        } catch (Exception e) {
            e.printStackTrace();
        }

        stopedServicesName = new ArrayList<String>();

    }

    @Override
    public IBinder onBind(Intent intent) {
        Log.i(TAG, TAG + " onBind.");
        return null;
    }

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        Log.i(TAG, TAG + " onStart.");
        try {
            if (powerLock == null)
                powerLock = new PowerLock(this, "NetTestService");
            powerLock.acquireWakeLock();
        } catch (Exception e) {
            e.printStackTrace();
        }

        serverConfigBean = NetTestUtil.getServerBean(getBaseContext());// 获取要测试的服务器配置信息

        allTestTimes = 1;
        ourServices = MyCommonUtil.getAllService(getBaseContext());// 获取所有service的对象
        stopedServicesName = new ArrayList<String>();// 每次开启服务都实例化一次有暂停的服务名称集合
        dbControl = new NetTestDBControl(getBaseContext());

        if (intent == null || intent.getStringExtra(PrivateActionName.SERVICE_ACTION) == null)
            return;

        String action = intent.getStringExtra(PrivateActionName.SERVICE_ACTION);

        if (action.equalsIgnoreCase(PrivateActionName.SERVICE_ACTION_STARTSERVICE)) {// 开始测速

            stopedServicesName = NetTestUtil.stopOtherService(getBaseContext(), ourServices,
                    this.getClass());
            countTestNum = intent.getIntExtra(PrivateActionName.NET_TEST_SERVICE_TESTNUM, 1);
            // 是否来自定时任务触发自动测试
            boolean isFromTimer = intent.getBooleanExtra(
                    PrivateActionName.NET_TEST_SERVICE_IS_TIME, false);

            // 如果是0那么就不进行测试，只是为了获取信号强度。
            if (countTestNum == 0) {
                return;
            }

            nextTimesID = dbControl.selectLastRowPid(NetTestDBConstant.TABLES_TESTTIMEINFO_NAME) + 1;
            initializeRoundData(isFromTimer);

            roundFileSize = 0;
            roundTimes = 0;

            int nextRoundID = dbControl
                    .selectLastRowPid(NetTestDBConstant.TABLES_TESTROUNDINFO_NAME) + 1;
            // 只有是来自页面人工点击才需要发送轮开始广播
            if (!isFromTimer) {
                firstSaveRound(nextRoundID);
            }
            startTest(isFromTimer, nextRoundID);
        }
        if (action.equalsIgnoreCase(PrivateActionName.SERVICE_ACTION_STOPSERVICE)) {// 关闭测速
            // 手动停止的时候，这一轮的平均数据
            int roundId = intent.getIntExtra(PrivateActionName.SERVICE_ACTION_ROUND_ID, 0);
            NetTestUtil.clearbadData(getBaseContext(), roundId);
            countTestNum = 0;
            if (threadTest != null && threadTest.isAlive()) {
                threadTest.interrupt();
            }
            if (mHandler != null) {
                mHandler.removeMessages(100);
            }
            countTestNum = 0;
            if (powerLock != null)
                powerLock.releaseWakeLock();

            stopService(true, roundId);
            NetTestUtil.startOtherService(getBaseContext(), stopedServicesName, ourServices);
        }

    }

    private void initializeRoundData(boolean isFromTimer) {
        if (netTestRoundInfoBean == null) {
            netTestRoundInfoBean = new NetTestRoundInfoBean();
            netTestRoundInfoBean.setStartTime(MyCommonUtil.getFormatDateTime());
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i(TAG, TAG + " onDestroy.");
        try {
            if (powerLock != null) {
                powerLock.releaseWakeLock();
            }
            powerLock = null;
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            if (threadTest != null && threadTest.isAlive()) {
                threadTest.interrupt();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            if (telManager != null && MyListener != null) {
                telManager.listen(MyListener, PhoneStateListener.LISTEN_NONE);
                telManager = null;
                MyListener = null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        stopForeground(true);
    }

    /**
     * 停止服务器
     * 
     * @param stopByMan 手动停止
     */
    private void stopService(boolean stopByMan, int nextRoundID) {
        Log.i(TAG, "stopService isAutoTest ");
        // 大于零才是 手动停止或者线程运行结束停止
        if (nextRoundID > 0) {
            endRound(nextRoundID);
        }
        NetTestUtil.setOneRoundFinishBroad(getBaseContext());
        // 开启log上传服务
        NetTestUtil.startUploadLogService(getBaseContext());
        stopSelf();
    }

    /*
     * 开始测试
     */
    private void startTest(boolean isAutoTest, int nextRoundID) {

        if (countTestNum > 0) {
            countTestNum--;
            testThread(isAutoTest, nextRoundID);
            nextTimesID = dbControl.selectLastRowPid(NetTestDBConstant.TABLES_TESTTIMEINFO_NAME) + 1;
        }

    }

    /*
     * 测试线程
     */
    private void testThread(final boolean isAutoTest, final int nextRoundID) {
        Log.i(TAG, "启动测试线程 isAutoTest= " + isAutoTest);
        threadTest = new Thread() {
            @Override
            public void run() {
                FTPClient ftpClient = null;
                boolean success = false;
                try {
                    if (MyCommonUtil.isNetworkAviable(getBaseContext())) {

                        netLogBeanInitial();

                        testDownFileName = MyCommonUtil.getDownFileName(MyCommonUtil
                                .getNetWorkType(getBaseContext()));
                        ftpClient = FtpUtil.ftpInitial(serverConfigBean.getServerAddress(),
                                serverConfigBean.getServerPort(),
                                serverConfigBean.getDownloadName(),
                                serverConfigBean.getDownloadPwd());
                        // 接通率（0表示成功，1表示失败）、掉线率（0表示掉线，1表示没掉线）
                        connectPercent = 1;
                        if (ftpClient != null) {
                            connectPercent = 0;
                            initialLogParameter(nextRoundID);
                            int reply = ftpClient.getReplyCode();
                            netLogBean.setReplyCode(String.valueOf(reply));
                            long beginTime = System.currentTimeMillis();
                            netLogBean.setReplyCode(test_ok_open);
                            NetTestUtil.saveLog(getBaseContext(), netLogBean);
                            success = testDownload(ftpClient, isAutoTest, beginTime);
                            long endTime = System.currentTimeMillis();
                            roundTimes = roundTimes + (endTime - beginTime);
                        } else {
                            netLogBean.setReplyCode(test_error_login);
                            // 发生一次接通不成功也要保存一次
                            NetTestUtil.saveLog(getBaseContext(), netLogBean);
                        }

                        dropPercent = 1; // （0表示掉线，1表示没掉线）
                        if (!success) {
                            dropPercent = 0;
                        } else {
                            netLogBean.setReplyCode(test_ok_finish);
                        }

                        // 测试完成需要保存一次，以便上传掉线率和未知错误
                        if (ftpClient != null)// 避免和接通不成功重复
                        {
                            NetTestUtil.saveLog(getBaseContext(), netLogBean);
                        }
                        // **一次测试完插入信息到time表，cell表和connect表**//

                        if (netTestTimesInfoBean != null) {
                            NetTestUtil.insertTimesInfo(netTestTimesInfoBean, getBaseContext());
                            netTestTimesInfoBean = null;
                        }

                        if (!NetTestUtil.hasNetTestCellInfosByTimes(getBaseContext(), nextTimesID,
                                netLogBean.getLac(), netLogBean.getCi())) {
                            NetTestUtil.insertCellInfo(oneTimesAverageSpeed, maxSpeed, minSpeed,
                                    maxNetStrong, minNetStrong, nextTimesID, getBaseContext(),
                                    netLogBean);
                        }
                        netTestConnectInfoBean.setConnectPercent(connectPercent);
                        netTestConnectInfoBean.setDropPercent(dropPercent);
                        NetTestUtil.insertConnectInfo(netTestConnectInfoBean, getBaseContext(),
                                netLogBean);
                        // ===============//

                        if (!success)
                            sleep(FtpConstant.NET_TEST_FTP__DEFAULT_SLEEP);

                    } else {
                        sleep(FtpConstant.NET_TEST_FTP__DEFAULT_SLEEP);
                    }

                } catch (Exception ex) {
                    ex.printStackTrace();
                } finally {
                    // if(!success)
                    // {
                    // //设置失败广播
                    // }
                    // 设置单次测试结束广播
                    Log.i("GYH", "allTestTimes=" + allTestTimes);
                    if (!isAutoTest) {
                        NetTestUtil.setOneTimesFinishBroad(getBaseContext(), allTestTimes, success);
                    }
                    FtpUtil.ftpDestroy(ftpClient);
                    actualTestTimes++;// 测试完成一次，实际测试次数加1
                    allTestTimes++;// 全部测试测试+1
                    // 只有大于零的时候才再次执行
                    Log.i("scj", "current countTestNum =" + countTestNum);
                    if (countTestNum > 0) {
                        Message msg = new Message();
                        msg.what = 100;
                        msg.arg1 = nextRoundID;
                        mHandler.sendMessage(msg); // 继续下一次测试
                    } else {
                        stopService(false, nextRoundID);
                    }
                }
            }

        };
        threadTest.start();
    }

    private void netLogBeanInitial() {
        netLogBean = new NetTestLogBean();
        netLogBean.setReplyCode(test_ok);
        netLogBean.setlogTime(MyCommonUtil.getCurDate());
        NetTestUtil.getLACCI(getBaseContext(), netLogBean);
        NetTestUtil.getNetworkInfo(getBaseContext(), netLogBean);
        netLogBean.setLatitude(String.valueOf(NetworkTestApp.getApp().getLatitude()));
        netLogBean.setLongitude(String.valueOf(NetworkTestApp.getApp().getLongitude()));
        netLogBean.setNetStrong(netStrong);
        netLogBean.setIpAddress(MyCommonUtil.getLocalIpAddress());
        netLogBean.setCity(NetworkTestApp.getApp().getCityName());
        netLogBean.setAPMAC(MyCommonUtil.getLocalMacAddress(NetTestService.this));
        if (serverConfigBean != null) {
            netLogBean.setServiceName(serverConfigBean.getServerName());
        }
    }

    /*
     * 测试下载，获取参数
     */
    private boolean testDownload(FTPClient ftpClient, boolean isAutoTest, long timeBegin) {
        long roundSpeedts = 0;
        int reply = -1;
        boolean success = false;
        // FileOutputStream fos = null;
        // BufferedOutputStream outStream = null;
        InputStream inputStream = null;
        BufferedInputStream buff = null;
        long remoteFileSize = 0;// 文件大小
        ArrayList<Double> fancai = new ArrayList<Double>();
        try {
            FTPFile[] remoteFile = ftpClient.listFiles(testDownFileName);
            if (remoteFile.length > 0) {
                remoteFileSize = remoteFile[0].getSize();
            }
            inputStream = ftpClient.retrieveFileStream(testDownFileName);
            int allsum = 0;
            int count = 0;

            while (count == 0) {
                count = inputStream.available();
            }

            long allstartTime = System.currentTimeMillis();// 总的开启时间
            long onestartTime = System.currentTimeMillis();// 用来对比log
            long speedonestartTime = System.currentTimeMillis();// 用来对比速率
            boolean isInterrupted = false;
            int onesize = 0;
            long timesize = 0;
            int oneSpeedSize = 0;
            if (inputStream != null) {
                byte[] b = new byte[fileFQsize];
                int j = 0;
                double temp = 0;
                maxSpeed = 0;
                minSpeed = 0;
                maxNetStrong = netStrong;
                minNetStrong = netStrong;

                long oneendTime = 0;
                long speedoneendTime = 0;
                long ts = 0;
                long speedts = 0;

                while ((!isInterrupted && (j = inputStream.read(b, 0, fileFQsize)) != -1)) {
                    oneendTime = System.currentTimeMillis();
                    speedoneendTime = oneendTime;
                    ts = oneendTime - onestartTime;
                    speedts = speedoneendTime - speedonestartTime;
                    roundSpeedts = roundTimes + (oneendTime - timeBegin);
                    onesize += j;
                    timesize = timesize + j;
                    oneSpeedSize += j;
                    roundFileSize += j;
                    allsum = allsum + j;
                    if (speedts >= 2000)// 每200ms对比一次speed
                    {
                        // 获取轮平均速度
                        temp = (double) ((double) roundFileSize / roundSpeedts / 1024 * 1000 * MyCommonConstant.NetTestConstant.addMultiple);
                        if (temp > 0) {
                            roundAverageSpeed = temp;// 过滤零值
                        }

                        oneTempSpeed = (double) ((double) oneSpeedSize / speedts / 1024 * 1000 * MyCommonConstant.NetTestConstant.addMultiple);
                        if (!timesFirstContrastSpeed) {
                            if (maxSpeed == 0)
                                maxSpeed = oneTempSpeed;
                            if (minSpeed == 0)
                                minSpeed = oneTempSpeed;
                            if (roundMaxSpeed == 0)
                                roundMaxSpeed = oneTempSpeed;
                            if (roundMinSpeed == 0)
                                roundMinSpeed = oneTempSpeed;

                            maxSpeed = (maxSpeed < oneTempSpeed) ? oneTempSpeed : maxSpeed;
                            minSpeed = (minSpeed > oneTempSpeed) ? oneTempSpeed : minSpeed;
                            roundMaxSpeed = (roundMaxSpeed < oneTempSpeed) ? oneTempSpeed
                                    : roundMaxSpeed;
                            roundMinSpeed = (roundMinSpeed > oneTempSpeed) ? oneTempSpeed
                                    : roundMinSpeed;
                        }
                        timesFirstContrastSpeed = false;
                        speedonestartTime = speedoneendTime;
                        oneSpeedSize = 0;
                        // 发送广播到前台提示当前速度
                        if (!isAutoTest) {
                            NetTestUtil.sendNetTestSpeedBroad(roundAverageSpeed, roundMaxSpeed,
                                    roundMinSpeed, getBaseContext().getString(R.string.ftp_down),
                                    getBaseContext());
                        }
                    }

                    if (ts >= 3000)// 每秒统计一次log
                    {

                        // Log.i(TAG, "当前记录的返回码是："+ftpClient.getReplyCode());
                        netLogBean.setReplyCode(test_ok);
                        netLogBean.setOneLogDownloadTime(String
                                .valueOf((oneendTime - onestartTime)));
                        netLogBean.setOneLogfileSize(String.valueOf(onesize));
                        if (NetworkTestApp.getApp().getLatitude() == 0) {
                            LocationUtil.getCurrentCity(getBaseContext());
                        }
                        netLogBean.setLatitude(String
                                .valueOf(NetworkTestApp.getApp().getLatitude()));
                        netLogBean.setLongitude(String.valueOf(NetworkTestApp.getApp()
                                .getLongitude()));
                        oneTimesAverageSpeed = (double) ((double) onesize / ts / 1024 * 1000 * 8);
                        fancai.add(oneTimesAverageSpeed);
                        netLogBean.setOneLogAveragespeed(oneTimesAverageSpeed);

                        netLogBean.setCostTime(1 + "");
                        netLogBean.setMinSpeed(minSpeed);
                        netLogBean.setMaxSpeed(maxSpeed);

                        NetTestUtil.saveLog(getBaseContext(), netLogBean);

                        onestartTime = oneendTime;
                        onesize = 0;
                    }
                    if (threadTest.isInterrupted()) {
                        isInterrupted = true;
                    }
                }
                b = null;
            }
            long allendTime = System.currentTimeMillis();
            if (!isInterrupted) {
                success = ftpClient.completePendingCommand();// 多文件下载执行
            }
            reply = ftpClient.getReplyCode();
            netTestTimesInfoBean.setReplayCode(reply);
            if (reply == 226) {
                success = true;
                long ts = allendTime - timeBegin;
                netTestTimesInfoBean.setDownLoadTime(String.valueOf((ts)));
                long fl = timesize - count;

                double temp1 = (double) ((double) roundFileSize / roundSpeedts / 1024 * 1000 * MyCommonConstant.NetTestConstant.addMultiple);
                if (temp1 > 0) {
                    roundAverageSpeed = temp1;// 过滤零值
                }
                // Log.i("scj", "time f1= "+fl+" count= "+count);
                // Log.i("scj", "time ts= "+ts);
                // Log.i("scj", "roundFileSize = "+roundFileSize);
                // Log.i("scj", "roundSpeedts = "+roundSpeedts);

                netTestTimesInfoBean.setFileSize(String.valueOf(timesize - count));
                netTestTimesInfoBean
                        .setAverageSpeed(((double) fl / ts / 1024 * 1000 * MyCommonConstant.NetTestConstant.addMultiple));
                netTestTimesInfoBean.setMaxSpeed(maxSpeed);
                netTestTimesInfoBean.setMinSpeed(minSpeed);
                netTestTimesInfoBean.setWaveShakeStrong(MyCommonUtil.getVarianceTwo(fancai));
                netTestTimesInfoBean.setNetType(netLogBean.getNetType());
                netTestTimesInfoBean.setDownServer(serverConfigBean.getServerName());
            } else {
                netLogBean.setReplyCode(test_error_fail);
                success = false;
                netTestTimesInfoBean.setNetType(netLogBean.getNetType());
                netTestTimesInfoBean.setDownServer(serverConfigBean.getServerName());
                netTestTimesInfoBean.setErrorReason(ftpClient.getReplyString());
                Log.d(TAG, TAG + "=>Download fail. Reply Code: " + ftpClient.getReplyString());
            }
            if (fancai != null) {
                fancai.clear();
            }
        } catch (SocketException e) {
            netLogBean.setReplyCode(test_error_miss);
            netTestTimesInfoBean.setErrorReason(e.getMessage());
            Log.i(TAG, "SocketException=>" + e.getMessage());
        } catch (IOException e) {
            netLogBean.setReplyCode(test_error_fail);
            netTestTimesInfoBean.setErrorReason(e.getMessage());
            Log.i(TAG, "IOException=>" + e.getMessage());
        } catch (Exception e) {
            netLogBean.setReplyCode(test_error_fail);
            netTestTimesInfoBean.setErrorReason(e.getMessage());
            Log.i(TAG, "Exception=>" + e.getMessage());
        } finally {
            try {
                // if (fos != null) {
                // fos.close();
                // }
                // if (outStream != null) {
                // outStream.close();
                // }
                if (inputStream != null) {
                    inputStream.close();
                }
                if (buff != null) {
                    buff.close();
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                Log.d(TAG, "testDownload finally close IOException: " + e.getMessage());
            }
        }
        return success;
    }

    /*
     * 初始化netLogBean、fileFQsize、netTestTimesInfoBean、netTestConnectInfoBean对象
     */
    private void initialLogParameter(int nextRoundID) {
        timesFirstContrastSpeed = true;
        oneTimesAverageSpeed = 0.0;
        fileFQsize = NetTestUtil.getNetworkInfo(getBaseContext(), netLogBean);

        netTestTimesInfoBean = new NetTestTimesInfoBean();
        netTestTimesInfoBean.setRoundID(nextRoundID);
        netTestConnectInfoBean = new NetTestConnecInfoBean();
    }

    /*
     * 结束一轮测试保存信息
     */
    private void endRound(int nextRoundID) {
        try {
            roundFileSize = 0;
            roundTimes = 0;
            if (netTestRoundInfoBean != null) {
                netTestRoundInfoBean.setPID(nextRoundID);
                netTestRoundInfoBean.setEndTime(MyCommonUtil.getFormatDateTime());
                netTestRoundInfoBean.setAverageSpeed(roundAverageSpeed);

                netTestRoundInfoBean.setMaxSpeed(roundMaxSpeed);
                netTestRoundInfoBean.setMinSpeed(roundMinSpeed);
                netTestRoundInfoBean.setTestTimes(actualTestTimes);
                netTestRoundInfoBean.setDownServer(serverConfigBean.getServerName());
                netTestRoundInfoBean.setConsumeTime(TimeUtil.secondBetweenTime(
                        netTestRoundInfoBean.getStartTime(), netTestRoundInfoBean.getEndTime()));

            }
            if (netTestRoundInfoBean != null && netTestRoundInfoBean.getTestTimes() > 0) {
                NetTestUtil.updateOrCreateTestRoundInfo(netTestRoundInfoBean, getBaseContext());
                netTestRoundInfoBean = null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return;
    }

    /*
     * 结束一轮测试保存信息
     */
    private void firstSaveRound(int nextRoundID) {
        NetTestRoundInfoBean bean = null;
        if (netTestRoundInfoBean != null) {
            netTestRoundInfoBean.setEndTime(MyCommonUtil.getFormatDateTime());
            netTestRoundInfoBean.setAverageSpeed(roundAverageSpeed);
            netTestRoundInfoBean.setMaxSpeed(roundMaxSpeed);
            netTestRoundInfoBean.setMinSpeed(roundMinSpeed);
            netTestRoundInfoBean.setTestTimes(actualTestTimes);
            netTestRoundInfoBean.setDownServer(serverConfigBean.getServerName());
            netTestRoundInfoBean.setConsumeTime(TimeUtil.secondBetweenTime(
                    netTestRoundInfoBean.getStartTime(), netTestRoundInfoBean.getEndTime()));
            netTestRoundInfoBean.setPID(nextRoundID);
        }
        if (netTestRoundInfoBean != null && (netTestRoundInfoBean.getStartTime() != null)) {
            NetTestUtil.insertRoundInfo(netTestRoundInfoBean, getBaseContext());
            // bean =
            // NetTestUtil.getNetTestRoundsInfosByStartTime(getBaseContext(),
            // netTestRoundInfoBean.getStartTime());
            // if (bean != null) {
            // netTestRoundInfoBean.setPID(bean.getPID());
            // }
        }
        // 发送一轮测试开始的广播
        NetTestUtil.setOneRoundBeginBroad(getBaseContext());
    }

    /**
     * 刷新handler
     * 
     * @param handler Handler对象
     * @param sig 标示为
     */
    public void sendMessage(Handler handler, int sig) {
        Message msg = new Message();
        msg.what = sig;
        handler.sendMessage(msg);
    }

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            if (msg.what == 100) {
                if (threadTest != null && threadTest.isAlive()) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                startTest(false, msg.arg1);
            }
        }
    };

    private String test_ok = "1100";// 测试正常(目前未细分统计前，所有测试正常的情况返回码均为1100)

    private String test_ok_open = "1101";// 测试正常(详细测试情况：数据链路埠开启，准备传送)

    private String test_ok_finish = "1102";// 测试正常(详细测试情况：关闭数据连接端口，请求的文件操作成功)

    private String test_error_fail = "1400";// 测试失败(仅在不确认失败原因时，使用该错误号)

    private String test_error_login = "1401";// 接通失败，即在发起FTP连接时发生错误(此时将这一秒的测试结果的返回码记录为该值)

    private String test_error_miss = "1402";// 发生掉线，即在FTP下载过程中出现异常导致(此时将这一秒的测试结果的返回码记录为该值)

}
